/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package PRESENT;

import UTILS.ErrorMessages;
import UTILS.StatusMessage;
import UTILS.GUIConstant;
import BUS.QuanBUS;
import DTO.QuanDTO;
import DTO.TinhDTO;
import UTILS.IDATAGUI;
import UTILS.IInitGUI;
import UTILS.IStateGUI;
import UTILS.ITableGUI;
import UTILS.SelectTableDialog;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;


/**
 *
 * @author HuuTri
 */
public class QuanGUI extends javax.swing.JFrame
                     implements IDATAGUI, IInitGUI, IStateGUI, ITableGUI {

    QuanGUIState currState;
    SelectTableDialog dialogTinh;
    
    /**
     * Creates new form QuanGUI
     */
    public QuanGUI() {
        initComponents();
        initCustom();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        panelButton = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtQuan_Error = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtSoLuongDaiLyToiDao_Error = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtMoTa = new javax.swing.JTextArea();
        txtTenQuan = new javax.swing.JTextField();
        txtMaTinh = new javax.swing.JComboBox();
        txtMaQuan = new javax.swing.JTextField();
        txtSoLuongDaiLyToiDa = new javax.swing.JTextField();
        btnXoaBo = new javax.swing.JButton();
        btnLuuLai = new javax.swing.JButton();
        btnThemMoi = new javax.swing.JButton();
        btnTableTinh = new javax.swing.JButton();
        txtId = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtMaQuan_Error = new javax.swing.JLabel();
        txtMaTinh_Error = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableQuan = new org.jdesktop.swingx.JXTable();
        txtStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(800, 600));

        jSplitPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jSplitPane1.setDividerLocation(320);
        jSplitPane1.setAutoscrolls(true);
        jSplitPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jSplitPane1.setMinimumSize(new java.awt.Dimension(0, 0));
        jSplitPane1.setPreferredSize(new java.awt.Dimension(0, 0));

        panelButton.setForeground(new java.awt.Color(255, 51, 51));
        panelButton.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel1.setText("Mã Quận: ");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel2.setText("Tên Quận: ");

        txtQuan_Error.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N
        txtQuan_Error.setForeground(new java.awt.Color(255, 51, 51));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel3.setText("Mô tả: ");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel4.setText("Số Lượng Đại Lý Tối Đa: ");
        jLabel4.setToolTipText("");

        txtSoLuongDaiLyToiDao_Error.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N
        txtSoLuongDaiLyToiDao_Error.setForeground(new java.awt.Color(255, 51, 51));

        txtMoTa.setColumns(20);
        txtMoTa.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
        txtMoTa.setLineWrap(true);
        txtMoTa.setRows(5);
        txtMoTa.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        jScrollPane3.setViewportView(txtMoTa);

        txtTenQuan.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
        txtTenQuan.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        txtTenQuan.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtTenQuanFocusLost(evt);
            }
        });

        txtMaTinh.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
        txtMaTinh.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        txtMaTinh.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                txtMaTinhItemStateChanged(evt);
            }
        });
        txtMaTinh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtMaTinhActionPerformed(evt);
            }
        });
        txtMaTinh.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtMaTinhFocusLost(evt);
            }
        });

        txtMaQuan.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
        txtMaQuan.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        txtMaQuan.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtMaQuanFocusLost(evt);
            }
        });
        txtMaQuan.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMaQuanKeyTyped(evt);
            }
        });
        txtMaQuan.setDocument(new PlainDocument() {
            public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
                if (str == null)
                return;
                str = str.toUpperCase();
                if ((getLength() + str.length()) <= GUIConstant.QUAN_MAQUAN_LENGTH_MAX) {
                    super.insertString(offset, str, attr);
                } else {
                    txtMaTinh_Error.setText(ErrorMessages.QUANGUI_TXTMAQUAN_ERROR_GREATER + GUIConstant.QUAN_MAQUAN_LENGTH_MAX);
                }
            }
        });

        txtSoLuongDaiLyToiDa.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
        txtSoLuongDaiLyToiDa.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        txtSoLuongDaiLyToiDa.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtSoLuongDaiLyToiDaFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtSoLuongDaiLyToiDaFocusLost(evt);
            }
        });
        txtSoLuongDaiLyToiDa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtSoLuongDaiLyToiDaKeyTyped(evt);
            }
        });

        btnXoaBo.setText("Xóa Bỏ");
        btnXoaBo.setToolTipText("CTRL + DELETE");
        btnXoaBo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaBoActionPerformed(evt);
            }
        });

        btnLuuLai.setText("Lưu Lại");
        btnLuuLai.setToolTipText("CTRL + S");
        btnLuuLai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLuuLaiActionPerformed(evt);
            }
        });

        btnThemMoi.setText("Thêm Mới");
        btnThemMoi.setToolTipText("CTRL + N");
        btnThemMoi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThemMoiActionPerformed(evt);
            }
        });

        btnTableTinh.setText("+");
        btnTableTinh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTableTinhActionPerformed(evt);
            }
        });

        txtId.setEditable(false);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel6.setText("Số định danh: ");

        txtMaQuan_Error.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N
        txtMaQuan_Error.setForeground(new java.awt.Color(255, 0, 0));

        txtMaTinh_Error.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N
        txtMaTinh_Error.setForeground(new java.awt.Color(255, 0, 0));

        javax.swing.GroupLayout panelButtonLayout = new javax.swing.GroupLayout(panelButton);
        panelButton.setLayout(panelButtonLayout);
        panelButtonLayout.setHorizontalGroup(
            panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelButtonLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtSoLuongDaiLyToiDao_Error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(panelButtonLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnThemMoi)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLuuLai)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnXoaBo))
                    .addGroup(panelButtonLayout.createSequentialGroup()
                        .addGroup(panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3)
                            .addComponent(txtSoLuongDaiLyToiDa)
                            .addComponent(txtTenQuan)
                            .addGroup(panelButtonLayout.createSequentialGroup()
                                .addGroup(panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtMaTinh_Error)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel4)
                                    .addComponent(txtQuan_Error, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel6)
                                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtMaQuan_Error))
                                .addGap(0, 26, Short.MAX_VALUE))
                            .addGroup(panelButtonLayout.createSequentialGroup()
                                .addComponent(txtMaTinh, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnTableTinh, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtMaQuan)))
                        .addContainerGap())))
        );
        panelButtonLayout.setVerticalGroup(
            panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelButtonLayout.createSequentialGroup()
                .addComponent(jLabel6)
                .addGap(7, 7, 7)
                .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(8, 8, 8)
                .addGroup(panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtMaTinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtMaQuan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnTableTinh))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMaQuan_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMaTinh_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtTenQuan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtQuan_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addGap(6, 6, 6)
                .addComponent(txtSoLuongDaiLyToiDa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtSoLuongDaiLyToiDao_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                .addGap(29, 29, 29)
                .addGroup(panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnXoaBo)
                    .addComponent(btnLuuLai)
                    .addComponent(btnThemMoi))
                .addContainerGap())
        );

        jSplitPane1.setLeftComponent(panelButton);

        tableQuan.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableQuan.setEditable(false);
        tableQuan.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableQuanMouseClicked(evt);
            }
        });
        tableQuan.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tableQuanKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(tableQuan);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
        );

        jSplitPane1.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtStatus)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtStatus)
                .addGap(26, 26, 26))
        );

        txtStatus.getAccessibleContext().setAccessibleName("txtStatus");

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    //<editor-fold defaultstate="collapsed" desc="implements interface IInitGUI">
    /*Khởi tạo các giá trị cơ bản*/
    @Override
    public void initCustom() {
        initState();
        initTable();
        initKeyBoards();
    }
    
    /*Khởi tạo các tổ hợp phím*/
    @Override
    public void initKeyBoards() {  
       btnLuuLai.setMnemonic(KeyEvent.VK_S);
       btnLuuLai.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK), "luulai");
       btnLuuLai.getActionMap().put("luulai", 
               new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        handleLuuLaiButton();
                    }                   
               });
       
       /*Thêm phím tắt cho thêm mới*/
       btnThemMoi.setMnemonic(KeyEvent.VK_N);
       btnThemMoi.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK), "themmoi");
       btnThemMoi.getActionMap().put("themmoi",
               new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        handleThemMoiButton();
                    }                   
               });
       
       /*Thêm phím tắt cho xóa*/
       btnXoaBo.setMnemonic(KeyEvent.VK_DELETE);
       btnXoaBo.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK), "xoabo");
       btnXoaBo.getActionMap().put("xoabo",
               new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        handleXoaBoButton();
                    }                   
               });
    }
    
    /*Khởi tạo bảng*/
    @Override
    public void initTable() {
        setStatus(StatusMessage.QUAN_TABLE_LOAD);
        tableQuan.setModel(QuanBUS.getTableModel());
        setStatus(StatusMessage.QUAN_DEFAULT);
    }
    
    /*Khởi tạo trạng thái*/
    @Override
    public void initState() {
        setSuspendedState();
        setRefreshState();
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="Kiểm tra các ô input">
    /*Kiểm tra các ô input*/
    private boolean checkAllField() {
        return ( checkTXTTenQuan() && checkTXTSLToiDa() && checkTXTMaQuan());
        // Giao các kết quả
    }
    
    private boolean checkTXTMaQuan() {
        if (txtMaQuan.getText().isEmpty()) {
            // trường hợp mã quận trống
            txtMaQuan_Error.setText(ErrorMessages.QUANGUI_TXTMAQUAN_ERROR_EMPTY);
            return false;
        } else if (txtMaQuan.getText().length() < GUIConstant.QUAN_MAQUAN_LENGTH_MIN) {
            // trường hợp mã quận nhỏ hơn giá trị nhỏ nhất
            txtMaQuan_Error.setText(ErrorMessages.QUANGUI_TXTMAQUAN_ERROR_LESS +
                    GUIConstant.QUAN_MAQUAN_LENGTH_MIN);
            return false;
        } else if (txtMaQuan.getText().length() > GUIConstant.QUAN_MAQUAN_LENGTH_MAX) {
            // trường hợp lớn hon giá trị cho phép
            txtMaQuan_Error.setText(ErrorMessages.QUANGUI_TXTMAQUAN_ERROR_GREATER + 
                    GUIConstant.QUAN_MAQUAN_LENGTH_MAX);
        } else if (!checkExistMaQuan()){
            // Nếu mã quận đã tồn tại
            txtMaQuan_Error.setText(ErrorMessages.QUANGUI_TXTMAQUAN_ERROR_EXIST);
            return false;
        } else {
            txtMaQuan_Error.setText("");
        }
        
        return true;
    }
    
    /*Kiểm tra mã quận có tồn tại hay không*/
    private boolean checkExistMaQuan() {
        return QuanBUS.checkExistMaQuan(txtId.getText(),
                                        txtMaQuan.getText(),
                                        txtMaTinh.getSelectedItem().toString()
                                        );
    }

    /*Kiểm tra tính hợp lệ của các ô nhập liệu tên quận*/
    private boolean checkTXTTenQuan() {
        if (txtTenQuan.getText().isEmpty()) {
            //Trường hợp ô tên quận bị bỏ trống
            txtQuan_Error.setText(ErrorMessages.QUANGUI_TXTQUAN_ERROR_NONE);
            return false;
        } else if (txtTenQuan.getText().length() < GUIConstant.QUAN_TEN_LENGHT_MIN) {
            //Trường hợp tên quân quá ngắn
            txtQuan_Error.setText(ErrorMessages.QUANGUI_TXTQUAN_ERROR_LESS + 
                                  GUIConstant.QUAN_TEN_LENGHT_MIN
                                  );
            return false;
        } else if (txtTenQuan.getText().length() > GUIConstant.QUAN_TEN_LENGHT_MAX) {
            //Trường hợp tên quận quá dài
            txtQuan_Error.setText(ErrorMessages.QUANGUI_TXTQUAN_ERROR_GREATER_THAN +
                    GUIConstant.QUAN_TEN_LENGHT_MAX);
            return false;
        } else {
            txtQuan_Error.setText("");
            return true;
        }
    }
    
    /*Kiểm tra tính hợp lệ của ô nhập liệu sl tói đa */
    private boolean checkTXTSLToiDa() {
        if (txtSoLuongDaiLyToiDa.getText().isEmpty()) {
            //Trường hợp bỏ trống số lượng đại lý tối đa
            txtSoLuongDaiLyToiDa.setText(String.valueOf(GUIConstant.QUAN_SLTOIDA_MIN));
            return false;
        } else if (txtSoLuongDaiLyToiDa.getText().length() > GUIConstant.QUAN_SLTOIDA_LENGTH_MAX) {
            //Trường hợp số lượng đại lý quá lớn
            txtSoLuongDaiLyToiDao_Error.setText(ErrorMessages.QUANGUI_TXTSLTOIDA_ERROR_GREATER_THAN +
                    GUIConstant.QUAN_SLTOIDA_MAX);
            return false;
        } else if (Integer.parseInt(txtSoLuongDaiLyToiDa.getText()) < GUIConstant.QUAN_SLTOIDA_MIN) {
            //Trường hợp số lượng đại lý quá nhỏ
            txtSoLuongDaiLyToiDao_Error.setText(ErrorMessages.QUANGUI_TXTSLTOIDA_ERROR_LESS_THAN + GUIConstant.QUAN_SLTOIDA_MIN);
            return false;
        } else {
            txtSoLuongDaiLyToiDao_Error.setText("");
            return true;
        }
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="implements IStateGUI">
    /*Refesh state*/
    @Override
    public void setRefreshState() {
        txtMaTinh.setModel(QuanBUS.getTinhList());
    }
    
    /*Trạng thái khởi động form*/
    @Override
    public void setSuspendedState() {
        currState = QuanGUIState.SUSPENDED;
        setEnabledState(false);
        btnLuuLai.setEnabled(false);
        btnXoaBo.setEnabled(false);
        btnThemMoi.setEnabled(true);
    }
    
    /*Trạng thái thêm một record mới*/
    @Override
    public void setCreationalState() {
        currState = QuanGUIState.CREATIONAL;
        setEnabledState(true);
        btnLuuLai.setEnabled(true);
        btnXoaBo.setEnabled(false);
        btnThemMoi.setEnabled(true);
        
        //Cập nhật các textfield
        txtId.setText(String.valueOf(QuanBUS.getNewMaQuan()));
        txtTenQuan.requestFocus();
        txtTenQuan.setText("");
        txtMoTa.setText("");
        txtSoLuongDaiLyToiDa.setText(String.valueOf(GUIConstant.QUAN_SLTOIDA_MIN));
        txtMaQuan.setText("");
    }
    
    /*Trạng thái khi một record trong bảng được chọn*/
    @Override
    public void setSelectionState() {
        currState = QuanGUIState.EDITABLE;
        setEnabledState(true);
        btnLuuLai.setEnabled(true);
        btnXoaBo.setEnabled(true);
        btnThemMoi.setEnabled(true);
    }
    
    /*Thiết lập trạng thái enable của các control*/
    @Override
    public void setEnabledState(boolean flag) {
        txtMaQuan.setEnabled(flag);
        txtMaTinh.setEnabled(flag);
        txtSoLuongDaiLyToiDa.setEnabled(flag);
        txtMoTa.setEnabled(flag);
        txtTenQuan.setEnabled(flag);
        btnTableTinh.setEnabled(flag);
        txtId.setEnabled(flag);
    }
    
    //</editor-fold>
        
    //<editor-fold defaultstate="collapsed" desc="implement ITableGUI Interface">
    /*Hiển thị thông tin*/
    @Override
    public void sendDataFromSelectedRecordOfTableToField() {
        int row = tableQuan.getSelectedRow(); // Lấy chỉ số hàng hiện tại được chọn
        if (row < 0) return;
        //Tải thông tin lên các control hiển thị
        String masoString = QuanBUS.getValue(   tableQuan.getModel(), 
                                                row, 
                                                QuanDTO.MA_QUAN
                                             ).toString();
        String[] maso = QuanBUS.getMaTinhAndMaQuanFromString(masoString);          

        //Chèn mã tỉnh
        String matinh = maso[0];
        txtMaTinh.setSelectedItem(matinh);
        
        //Chèn mã quận
        if (maso.length > 1) {
            String maquan = maso[1];
            txtMaQuan.setText(maquan);
        }
        
        //Chèn số định danh
        String sodinhdanh = QuanBUS.getValue(tableQuan.getModel(), row, QuanDTO.ID).toString();
        txtId.setText(sodinhdanh);
        //chèn tên quận
        String tenquan = QuanBUS.getValue(tableQuan.getModel(), row, QuanDTO.TEN_QUAN).toString();
        txtTenQuan.setText(tenquan);
        
        //chèn số lượng đại lý tối đa
        String soluongdailytoida = QuanBUS.getValue(tableQuan.getModel(), row, QuanDTO.SLDAILY_TOIDA).toString();
        txtSoLuongDaiLyToiDa.setText(soluongdailytoida);
        
        //chèn mô tả quận
        String mota = QuanBUS.getValue(tableQuan.getModel(), row, QuanDTO.MO_TA).toString();
        txtMoTa.setText(mota);
        
        //add checkModifiedContent
    }
    
    /*Cập nhật thông tin từ field lên bảng*/
    @Override
    public void sendDataFromFieldToSelectedRecordOfTable() {
        int row = tableQuan.getSelectedRow();
        if (row < 0) return;
        
        QuanBUS.setValue(tableQuan.getModel(),
                row,
                QuanDTO.ID,
                txtId.getText()
                );
        
        QuanBUS.setValue(tableQuan.getModel(),
                row,
                QuanDTO.MA_QUAN,
                QuanBUS.getStringOfMaQuanAndMaTinh(
                txtMaQuan.getText(),
                txtMaTinh.getSelectedItem().toString()
                )
                );
        QuanBUS.setValue(tableQuan.getModel(),
                row,
                QuanDTO.MO_TA,
                txtMoTa.getText()
                );
        QuanBUS.setValue(tableQuan.getModel(),
                row,
                QuanDTO.TEN_QUAN,
                txtTenQuan.getText()
                );
        QuanBUS.setValue(tableQuan.getModel(),
                row,
                QuanDTO.SLDAILY_TOIDA,
                txtSoLuongDaiLyToiDa.getText()
                );
    }
    
    /**
     * Chuyển dữ liệu từ field lên table
     */
    @Override
    public void sendDataFromFieldToNewRecordOfTable() {
        ((DefaultTableModel)tableQuan.getModel()).addRow(new Object[] {
            txtId.getText(),
            QuanBUS.getStringOfMaQuanAndMaTinh(
                txtMaQuan.getText(),
                txtMaTinh.getSelectedItem().toString()
                ),
            txtTenQuan.getText(),
            txtSoLuongDaiLyToiDa.getText(),
            txtMoTa.getText()
        });
        setStatus(StatusMessage.QUAN_DEFAULT);
    }
    
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="implement interface IDATAGUI">
    @Override
    public boolean insertRecord() {
        setStatus(StatusMessage.QUAN_TABLE_SAVE);
               
       // Cập nhật thông tin bảng hiển thị
       sendDataFromFieldToNewRecordOfTable();
       
        // Thêm thông tin vào database
       return QuanBUS.insertRecord(
               txtId.getText(), txtMaQuan.getText(),
               txtTenQuan.getText(), txtSoLuongDaiLyToiDa.getText(), 
               txtMaTinh.getSelectedItem().toString(), txtMoTa.getText());

    }
    
    @Override
    public boolean deleteRecord() {
        setStatus(StatusMessage.QUAN_TABLE_SAVE);

        //Xóa thông tin khỏi bảng hiển thị
        ((DefaultTableModel)tableQuan.getModel()).removeRow(tableQuan.getSelectedRow());
        
        return QuanBUS.deleteRecord(txtId.getText()); // xoá quận khỏi danh sách dựa vào mã quận
    }
    
    @Override
    public boolean updateRecord() {
        setStatus(StatusMessage.QUAN_TABLE_SAVE);
        
        return QuanBUS.updateRecord(
                txtId.getText(),
                txtMaQuan.getText(), txtTenQuan.getText(),
                txtMaTinh.getSelectedItem().toString(), 
                txtSoLuongDaiLyToiDa.getText(), txtMoTa.getText()
                ); // Cập nhật xuống database   
    }
    //</editor-fold>
    
    /*Cập nhật thông báo trạng thái*/
    public void setStatus(String status) {
        txtStatus.setText(status);
    }
    
    //<editor-fold defaultstate="collapsed" desc="Event">
    private void txtMaTinhFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaTinhFocusLost
        if (txtMaTinh.getSelectedIndex() < 0) {
            //Trường hợp combobox bị rơi vào index -1
            txtMaTinh_Error.setText(ErrorMessages.QUANGUI_TXTMATINH_ERROR_NONE);
        } else {
            txtMaTinh_Error.setText("");
        }
    }//GEN-LAST:event_txtMaTinhFocusLost

    private void txtTenQuanFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTenQuanFocusLost
        checkTXTTenQuan(); // Kiểm tra tính hợp lệ của ô tên quận
        txtMaQuan.setText(QuanBUS.getMaQuanFromTenQuan(txtTenQuan.getText()));
    }//GEN-LAST:event_txtTenQuanFocusLost

    private void txtSoLuongDaiLyToiDaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtSoLuongDaiLyToiDaFocusLost
       checkTXTSLToiDa(); // Kiểm tra tính hợp lên của ô sô lượng tối đa
    }//GEN-LAST:event_txtSoLuongDaiLyToiDaFocusLost

    private void txtSoLuongDaiLyToiDaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSoLuongDaiLyToiDaKeyTyped
        handleSoLuongDaiLyToiDaKeyTyped(evt);
    }//GEN-LAST:event_txtSoLuongDaiLyToiDaKeyTyped

    private void txtMaQuanKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMaQuanKeyTyped

    }//GEN-LAST:event_txtMaQuanKeyTyped

    private void btnThemMoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemMoiActionPerformed
        handleThemMoiButton();
    }//GEN-LAST:event_btnThemMoiActionPerformed

    private void btnXoaBoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaBoActionPerformed
        handleXoaBoButton();
    }//GEN-LAST:event_btnXoaBoActionPerformed

    private void tableQuanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableQuanMouseClicked
        handleTableSelected();
    }//GEN-LAST:event_tableQuanMouseClicked

    private void btnLuuLaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuLaiActionPerformed
        handleLuuLaiButton();
    }//GEN-LAST:event_btnLuuLaiActionPerformed

    private void txtMaTinhActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMaTinhActionPerformed
      
    }//GEN-LAST:event_txtMaTinhActionPerformed

    private void tableQuanKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableQuanKeyPressed
       handleTableSelected();
    }//GEN-LAST:event_tableQuanKeyPressed

    private void btnTableTinhActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTableTinhActionPerformed
        handleBtnTableTinhActionPerformed(evt);
    }//GEN-LAST:event_btnTableTinhActionPerformed

    private void txtMaQuanFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaQuanFocusLost
        checkTXTMaQuan();
    }//GEN-LAST:event_txtMaQuanFocusLost

    private void txtSoLuongDaiLyToiDaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtSoLuongDaiLyToiDaFocusGained
        handleTxtSoLuongDaiLyToiDaFocusGained();
    }//GEN-LAST:event_txtSoLuongDaiLyToiDaFocusGained

    private void txtMaTinhItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_txtMaTinhItemStateChanged

    }//GEN-LAST:event_txtMaTinhItemStateChanged
        //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="Handle of Event">
    
    private void handleTxtSoLuongDaiLyToiDaFocusGained() {
        if (String.valueOf(GUIConstant.QUAN_SLTOIDA_MIN).
                equals(txtSoLuongDaiLyToiDa.getText())) {
            txtSoLuongDaiLyToiDa.setText("");
        }
    }
    
    
    private void handleBtnTableTinhActionPerformed(ActionEvent evt) {
         if(dialogTinh == null) {
             dialogTinh = new SelectTableDialog(this, true, TinhDTO.TABLE);
         }
         dialogTinh.setVisible(true);
         txtMaTinh.setSelectedItem(dialogTinh.getSelectedItem(TinhDTO.MA_TINH));
    }
    
    /**
     * Thực thi xử lí sự kiện table được chọn
     */
    private void handleTableSelected() {
        if (tableQuan.getSelectedRow() < 0) return;
        setSelectionState();
        sendDataFromSelectedRecordOfTableToField(); //Chuyển thông tin từ table lên các ô thông tin 
    }
    
    /*Thực thi nút Lưu lại*/
    private void handleLuuLaiButton() {
        if (currState == QuanGUIState.SUSPENDED) return;
        // Nếu như đang ở trạng thái tạo mới thì insert record mới
        if (!checkAllField()) return;
        if (currState == QuanGUIState.CREATIONAL) { // đang ở trạng thái tạo mới
            insertRecord();
            setCreationalState();
        } else if (currState == QuanGUIState.EDITABLE) { // đang ở trạng thái cập nhật
            updateRecord();
            sendDataFromFieldToSelectedRecordOfTable();
        }
    }
    
    /*Thực thi xử lí tổ hợp phím*/
    private void handleKeyPress(KeyEvent evt) {
          if ((evt.getModifiers() & KeyEvent.CTRL_DOWN_MASK)!= 0) {
            switch (evt.getKeyCode()) {
                case KeyEvent.VK_S: handleLuuLaiButton(); break;
            }
        }
    }
    
    /*Thực thi xử lí thêm mới*/
    private void handleThemMoiButton() {
        setCreationalState();
    }
    
    /*Thực thi xóa bỏ*/
    private void handleXoaBoButton() {
        setCreationalState();
        deleteRecord();
    }
    
    /**
     * Thực thi sự kiện chọn record trong table
     * @param evt 
     */
    private void handleSoLuongDaiLyToiDaKeyTyped(KeyEvent evt) {
        if (!(Character.isDigit(evt.getKeyChar()) || 
                Character.isISOControl(evt.getKeyChar()))) {
            txtSoLuongDaiLyToiDao_Error.setText(ErrorMessages.QUANGUI_TXTSLTOIDA_ERROR_TEXT);
            evt.consume();
        } else {
            txtSoLuongDaiLyToiDao_Error.setText("");
        }
    }
    //</editor-fold>
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(QuanGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(QuanGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(QuanGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(QuanGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new QuanGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLuuLai;
    private javax.swing.JButton btnTableTinh;
    private javax.swing.JButton btnThemMoi;
    private javax.swing.JButton btnXoaBo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JPanel panelButton;
    private org.jdesktop.swingx.JXTable tableQuan;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtMaQuan;
    private javax.swing.JLabel txtMaQuan_Error;
    private javax.swing.JComboBox txtMaTinh;
    private javax.swing.JLabel txtMaTinh_Error;
    private javax.swing.JTextArea txtMoTa;
    private javax.swing.JLabel txtQuan_Error;
    private javax.swing.JTextField txtSoLuongDaiLyToiDa;
    private javax.swing.JLabel txtSoLuongDaiLyToiDao_Error;
    private javax.swing.JLabel txtStatus;
    private javax.swing.JTextField txtTenQuan;
    // End of variables declaration//GEN-END:variables

}
enum QuanGUIState {
    SUSPENDED,
    CREATIONAL,
    EDITABLE
}